package me.abel.auditing.config;

import me.abel.auditing.entity.BaseEntity;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.aspectj.ConfigurableObject;
import org.springframework.util.Assert;

import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;

@Configurable
public class CustomAuditingListener implements ConfigurableObject {

    private ObjectFactory<CustomAuditingHandler> handler;

    @Autowired
    public void setAuditingHandler(ObjectFactory<CustomAuditingHandler> auditingHandler) {

        Assert.notNull(auditingHandler, "AuditingHandler must not be null!");
        this.handler = auditingHandler;
    }

    @PrePersist
    private void prePersist(BaseEntity obj) {
        handler.getObject().markCreated(obj);
    }
    @PreUpdate
    private void preUpdate(BaseEntity obj) {
        handler.getObject().markModified(obj);
    }
}

